<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2020-09-01 08:42:42
 * @LastEditors: Sam
 * @LastEditTime: 2023-02-09 19:19:24
 */
namespace app\common\support;
use think\Exception;
use think\facade\Log;
use think\facade\Config;
use think\facade\Db;
use think\facade\Loader;
use think\facade\Request;
use think\facade\Env;
use think\BaseController;
use app\admin\model\AuthRule as AuthRuleModel;

class Generate
{
    private $module;
    private $name;
    private $dir;
    private $namespaceSuffix;
    private $nameLower;
    private $data;
    private $default_module = 'common';
    // 控制器黑名单
    private $blacklistName = [
        'Admin',
        'Api',
        'Base',
        'Curd',
        'Index',
        'System',
    ];
    // 数据表黑名单
    private $blacklistTable = [
        'admin',
        'mg_member',
        'mg_group',
        'mg_menu'
    ];

    public function run($data)
    {
        $app_path = dirname(dirname($_SERVER['SCRIPT_FILENAME'])) . DS . 'app';
       
        // 检查目录是否可写
        if (!self::checkWritable($app_path)) {
            exception($app_path . "目录没有权限不可写，请执行一下命令修改权限：<br>chmod -R 755 ");
        }

        $dir_list[] = $app_path . DS . $data['module'] . DS . 'controller';
        $dir_list[] = $app_path . DS . $data['module'] . DS . 'model';
        $dir_list[] = $app_path . DS . 'common' . DS . 'view' .DS. 'src';
        $dir_list[] = $app_path . DS . 'common' . DS . 'view' .DS. 'src' .DS. 'views'.DS.  strtolower($data['controller']);
        $dir_list[] = $app_path . DS . 'common' . DS . 'view' .DS. 'src' .DS.  'views'.DS. strtolower($data['controller']).DS.'components';
        $dir_list[] = $app_path . DS . 'common' . DS . 'view' .DS. 'src' .DS .'api';
    
        
        //删除之前生成的文件
        _rmdir($app_path . DS .'app'.DS. 'common' . DS . 'view' .DS. 'src' .DS.'api');
        _rmdir($app_path . DS .'app'.DS. 'common' . DS . 'view' .DS. 'src' .DS.'views');
        // 创建目录
        $this->buildDir($dir_list);

        // 创建目录
        
        // 将菜单全部转为小写
        $this->data      = $data;
        $this->module    = $data['module'];
        $controllers     = explode('.', $data['controller']);
        $this->name      = array_pop($controllers);
        $this->nameLower = parseName($this->name);

        // 分级控制器目录和命名空间后缀
        if ($controllers) {
            $this->dir             = strtolower(implode(DS, $controllers) . DS);
            $this->namespaceSuffix = "\\" . strtolower(implode("\\", $controllers));
        } else {
            $this->dir             = "";
            $this->namespaceSuffix = "";
        }


        // 数据表表名
        $tableName = $data['table_name'] ? $data['table_name'] : $data['controller'];

        // 判断是否在黑名单中
        if (in_array($data['controller'], $this->blacklistName)) {
            json_response(0, '该控制器不允许创建');
        }

        // 判断是否在数据表黑名单中
        if (isset($tableName) && $tableName && in_array(parseName($tableName), $this->blacklistTable)) {
            json_response(0, '该数据表不允许创建');
        }

        if (strstr($data['controller'], '.')) {
            $spi      = explode('.', $data['controller']);
            $pathView = $app_path . DS . $this->module . DS . "view" . DS . $spi[0] . DS . $spi[1];
            $fileName = $app_path . DS . "%MODULE%" . DS . "%NAME%" . DS . $spi[0] . DS . ucfirst($spi[1]) . ".php";
        } else {
            $pathView = $app_path . DS . $this->module . DS . "view" . DS . $data['controller'] . DS;
            $fileName = $app_path . DS . "%MODULE%" . DS . "%NAME%" . DS . ucfirst($data['controller']) . ".php";
        }

        $pathTemplate = $app_path . DS . "common" . DS . "view" . DS . "template" . DS;

        $code = $this->parseCode();
        // dump($code);die;
       
        // 执行方法
       return $this->buildAll($pathView, $pathTemplate, $fileName, $tableName, $code, $data);
    }


    /**
     * 检查当前模块目录是否可写
     * @return bool
     */
    public static function checkWritable($path = '')
    {
        $app_path = dirname(dirname($_SERVER['SCRIPT_FILENAME']) . DS);
        try {
            $path     = $path ? $path : $app_path . DS . 'admin' . DS;
            $testFile = $path . "bulid.test";
            if (!file_put_contents($testFile, "test")) {
                return false;
            }
            // 解除锁定
            unlink($testFile);

            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 创建路由 
     * @param [type] $pathView
     * @param [type] $pathTemplate
     * @param [type] $fileName
     * @param [type] $tableName
     * @param [type] $code
     * @param [type] $data
     * @return void
     * @author Sam
     * @date 2022-04-12
     */
    public function buildRoute($pathView, $pathTemplate, $fileName, $tableName, $code, $data){
        $app_path   = dirname(dirname($_SERVER['SCRIPT_FILENAME']) . DS);
        $route_path = $app_path.DS.'app'.DS.$data['module'].DS.'route'.DS.'route.php';
        $template   = file_get_contents($route_path);
        $controller = $data['controller'];
        $extra      = '';
 
        if($data['import_button']){
            $extra .= 'Route::post(\'/'.strtolower($controller).'_import\', $common."'.$controller.'@import_excell")->name("'.strtolower($controller).'.import");// 导入';
        }
        $str        =  '
    Route::group(function () {
        //'.$data['menu_name'].'
            $common = "\\\app\\\admin\\\controller\\\";
            Route::get("/'.strtolower($controller).'_index", "app\admin\controller\\'.$controller.'@index")->name("'.strtolower($controller).'.index");// 列表
            Route::get("/'.strtolower($controller).'_detail", "app\admin\controller\\'.$controller.'@detail")->name("'.strtolower($controller).'.detail");// 详情
            Route::post("/'.strtolower($controller).'_delete", "app\admin\controller\\'.$controller.'@delete")->name("'.strtolower($controller).'.delete");// 删除
            Route::post("/'.strtolower($controller).'_create", "app\admin\controller\\'.$controller.'@create")->name("'.strtolower($controller).'.create");// 创建  
            Route::post("/'.strtolower($controller).'_edit", "app\admin\controller\\'.$controller.'@edit")->name("'.strtolower($controller).'.edit");
            '.$extra.'
        })
    ->allowCrossDomain() // 跨域
    ->middleware(middleware\Auth::class)// jwt认证
    ->middleware(middleware\Permission::class);// 权限认证
        ';
        if($data['export_button']){
          $str .= '
          Route::group(function () {
              //'.$data['menu_name'].'
                  Route::get("/'.strtolower($controller).'_export", "app\admin\controller\\'.$controller.'@export_excell")->name("'.strtolower($controller).'.export");// 导出
              });
              ';
        }
 
         file_put_contents($route_path, $str, FILE_APPEND);
    }

    /**
     * 创建前端文件 
     * @param [type] $pathView
     * @param [type] $pathTemplate
     * @param [type] $fileName
     * @param [type] $tableName
     * @param [type] $code
     * @param [type] $data
     * @return void
     * @author Sam
     * @date 2022-04-12
     */
    public function buildView($pathView, $pathTemplate, $fileName, $tableName, $code, $data){
        $template               = file_get_contents($pathTemplate . "index.tpl");
        $template_router        = file_get_contents($pathTemplate . "router.tpl");
        $template_create        = file_get_contents($pathTemplate . "create.tpl");
        $template_edit        = file_get_contents($pathTemplate . "edit.tpl");
        $template_api           = file_get_contents($pathTemplate . "api.tpl");
        $app_path = dirname(dirname($_SERVER['SCRIPT_FILENAME']) . DS);
        $view_tpl = $app_path . DS .'app'.DS. 'common' . DS . 'view' .DS. 'src' .DS. 'views'.DS. strtolower($data['controller']);
        $file            = $view_tpl.DS."index.vue";
        $file_router     = $view_tpl.DS."router.js";
        $file_create     = $view_tpl.DS.'components'.DS."create.vue";
        $file_edit       = $view_tpl.DS.'components'.DS."edit.vue";
        $file_api        = $app_path . DS .'app'.DS. 'common'.DS.'view' . DS .'src'. DS . 'api' .DS . strtolower($data['controller']).'.js';
        
        file_put_contents($file, str_replace(
            ["[NAME]", "[WHEREITEM]", "[TABLE_ITEM]", "[CONTROLLER]","[DETAIL]","[CREATEBUTTON]","[EDITBUTTON]","[DETAILBUTTON]","[DELETEBUTTON]","[BATCHBUTTON]","[EXPORTBUTTON]","[IMPORTBUTTON]","[DETAILDIALOG]","[EDITLDIALOG]","[CREATEDIALOG]","[IMPORT]","[INDEXCOMPONENTS]","[INDEXDATA]","[INDEXBATCH]","[INDEXMETHODS]","[BATCHSELECT]"],
            [$data['menu_name'], $code['where_item'], $code['table_item'], strtolower($data['controller']),$code['detail_data'],$code['create_button'],$code['edit_button'],$code['detail_button'],$code['delete_button'],$code['batch_button'],$code['export_button'],$code['import_button'],$code['detail_dialog'],$code['edit_dialog'],$code['create_dialog'],$code['import'],$code['index_components'],$code['index_data'],$code['index_batch'],$code['index_method'],$code['batch_select']],
            $template
            )
        );
        if(isset($data['detail_button']) && $data['detail_button'] && $code['detail_data']){
            file_put_contents($file,str_replace(["DETAIL"],[$code['detail_data']],file_get_contents($file)));
        }
        file_put_contents($file_router, str_replace(
            ["[NAME]", "[CONTROLLER]", "[ICON]"],
            [$data['menu_name'], strtolower($data['controller']),$data['icon']],
            $template_router
            )
        );
        if(isset($data['create_button']) && $data['create_button']){
            file_put_contents($file_create, str_replace(
                ["[FORMITEM]", "[IMPORTITEM]", "[COMPONENTS]", "[VALIDATE]", "[FORMDATA]","[CMETHODS]","[SUBMITDATA]","[CONTROLLER]"],
                [$code['form_item'], $code['import_item'],$code['components'],$code['validate'],$code['form_data'],$code['create_methods'],$code['submit_data'],strtolower($data['controller'])],
                $template_create
                )
            );
        }
        
        if(isset($data['edit_button']) && $data['edit_button']){
            file_put_contents($file_edit, str_replace(
                ["[FORMITEM]", "[IMPORTITEM]", "[COMPONENTS]", "[VALIDATE]", "[FORMDATA]","[EMETHODS]","[SUBMITDATA]","[CONTROLLER]","[EDITDATA]"],
                [$code['form_item'], $code['import_item'],$code['components'],$code['validate'],$code['form_data'],$code['edit_methods'],$code['submit_data'],strtolower($data['controller']),$code['edit_data']],
                $template_edit
                )
            );
        }
      
        file_put_contents($file_api, str_replace(
            [ "[CONTROLLER]"],
            [ strtolower($data['controller'])],
            $template_api
            )
        );
 
    }   
    /**
     * 生成所有文件
     */
    private function buildAll($pathView, $pathTemplate, $fileName, $tableName, $code, $data)
    {
       
        $this->buildController($pathView, $pathTemplate, $fileName, $tableName, $code, $data);
        
        $this->buildModel($pathView, $pathTemplate, $fileName, $tableName, $data);
        
        $this->buildTable($pathView, $pathTemplate, $fileName, $tableName, $code, $data);

        $this->buildRoute($pathView, $pathTemplate, $fileName, $tableName, $code, $data);
   
        $build_view =  $this->buildView($pathView, $pathTemplate, $fileName, $tableName, $code, $data);
  
        if (!Db::name('auth_rule')->where('title', $data['menu_name'])->count()) {
        
            $result = AuthRuleModel::query()->create([
                'parent_id'    => 0,
                'title'        => $data['menu_name'],
                'url'          => '#',
                'method'       => 'GET',
                'slug'         => strtolower($data['controller']),
                'description'  => $data['description'] ?? '',
                'listorder'    => $data['listorder'] ?? 100,
                'is_need_auth' => $data['is_need_auth'] ?? 0,
                'is_system'    => $data['is_system'] ?? 0,
            ]);
            $result = AuthRuleModel::query()->create([
                'parent_id'    => $result->id,
                'title'        => $data['menu_name'].'列表',
                'url'          => '/'.strtolower($data['controller']).'_index',
                'method'       => 'GET',
                'slug'         => strtolower($data['controller']).'.index',
                'description'  => $data['description'] ?? '',
                'listorder'    => $data['listorder'] ?? 100,
                'is_need_auth' => $data['is_need_auth'] ?? 0,
                'is_system'    => $data['is_system'] ?? 0,
            ]);
            AuthRuleModel::query()->create([
                'parent_id'    => $result->id,
                'title'        => $data['menu_name'].'创建',
                'url'          => '/'.strtolower($data['controller']).'_create',
                'method'       => 'POST',
                'slug'         => strtolower($data['controller']).'.create',
                'description'  => $data['description'] ?? '',
                'listorder'    => $data['listorder'] ?? 100,
                'is_need_auth' => $data['is_need_auth'] ?? 0,
                'is_system'    => $data['is_system'] ?? 0,
            ]);
            AuthRuleModel::query()->create([
                'parent_id'    => $result->id,
                'title'        => $data['menu_name'].'详情',
                'url'          => '/'.strtolower($data['controller']).'_detail',
                'method'       => 'GET',
                'slug'         => strtolower($data['controller']).'.detail',
                'description'  => $data['description'] ?? '',
                'listorder'    => $data['listorder'] ?? 100,
                'is_need_auth' => $data['is_need_auth'] ?? 0,
                'is_system'    => $data['is_system'] ?? 0,
            ]);
            AuthRuleModel::query()->create([
                'parent_id'    => $result->id,
                'title'        => $data['menu_name'].'编辑',
                'url'          => '/'.strtolower($data['controller']).'_edit',
                'method'       => 'POST',
                'slug'         => strtolower($data['controller']).'.edit',
                'description'  => $data['description'] ?? '',
                'listorder'    => $data['listorder'] ?? 100,
                'is_need_auth' => $data['is_need_auth'] ?? 0,
                'is_system'    => $data['is_system'] ?? 0,
            ]);
            AuthRuleModel::query()->create([
                'parent_id'    => $result->id,
                'title'        => $data['menu_name'].'删除',
                'url'          => '/'.strtolower($data['controller']).'_delete',
                'method'       => 'POST',
                'slug'         => strtolower($data['controller']).'.delete',
                'description'  => $data['description'] ?? '',
                'listorder'    => $data['listorder'] ?? 100,
                'is_need_auth' => $data['is_need_auth'] ?? 0,
                'is_system'    => $data['is_system'] ?? 0,
            ]);
            if($data['export_button']){
                AuthRuleModel::query()->create([
                    'parent_id'    => $result->id,
                    'title'        => $data['menu_name'].'导出 ',
                    'url'          => '/'.strtolower($data['controller']).'_export',
                    'method'       => 'GET',
                    'slug'         => strtolower($data['controller']).'.export',
                    'description'  => $data['description'] ?? '',
                    'listorder'    => $data['listorder'] ?? 100,
                    'is_need_auth' => $data['is_need_auth'] ?? 0,
                    'is_system'    => $data['is_system'] ?? 0,
                ]);
            }
            if($data['import_button']){
                AuthRuleModel::query()->create([
                    'parent_id'    => $result->id,
                    'title'        => $data['menu_name'].'导入 ',
                    'url'          => '/'.strtolower($data['controller']).'_import',
                    'method'       => 'GET',
                    'slug'         => strtolower($data['controller']).'.import',
                    'description'  => $data['description'] ?? '',
                    'listorder'    => $data['listorder'] ?? 100,
                    'is_need_auth' => $data['is_need_auth'] ?? 0,
                    'is_system'    => $data['is_system'] ?? 0,
                ]);
            }
        }
        return compact('build_view','data');
        

    }


    /**
     * 创建目录
     */
    private function buildDir($dir_list)
    {
        foreach ($dir_list as $dir) {
            if (!file_exists($dir)) {
                mkdir($dir, 0777, true);
            }
        }
    }


    /**
     * 创建控制器文件
     */
    private function buildController($path, $pathTemplate, $fileName, $tableName, $code, $data)
    {
  
        $module = $data['module'];
        $template        = file_get_contents($pathTemplate . "Controller.tpl");
        $file            = str_replace(
            ['%MODULE%', '%NAME%'],
            [$this->module, 'controller'],
            $fileName
        );
        $module          = $data['module'];
        $controller_name = ucfirst($data['controller']);
        $flex            = '';
        $controller      = ucfirst($data['controller']);
        $table           = ucfirst($controller_name);
        $utable          = ucfirst($table);
        // dump($code);die;
        return file_put_contents($file, str_replace(
                ["[MODULE]", "[CONTROLLER]", "[CONTROLLERLO]", "[UTABLE]", "[SEARCH]", "[FORMITEM]","[VALIDATEDATA]","[VALIDATEMSG]"],
                [$module, $controller_name, $data['controller'], $utable,  $code['search'], $code['form_item'],$code['validate_data'],$code['validate_msg']],
                $template
            )
        );
    }


    /**
     * 创建模型文件
     */
    private function buildModel($path, $pathTemplate, $fileName, $tableName, $data)
    {

        $app_path = dirname(dirname($_SERVER['SCRIPT_FILENAME']) . DS);
        // 直接生成空模板
        $template = file_get_contents($pathTemplate . "Model.tpl");

        // 获取模型的路径，根据配置文件读取
        $module     = $data['module'];
        $controller = $data['controller'];

        // $table  = ucfirst($data['table_name'] ?: $data['controller']);
        $table = ucfirst($data['controller']);
        if (strstr($data['controller'], '.')) {
            $spi  = explode('.', $data['controller']);
            $flex = '\\' . $spi[0];
            $file = $app_path . DS . 'app' . DS . $module . DS . "model" . DS . ucfirst($spi[0]) . DS . $table . ".php";
        } else {
            $file = $app_path . DS . 'app' . DS . $module . DS . "model" . DS . ucfirst($table) . ".php";
            $flex = '';
        }

        $autoTimestamp = '';
        if (isset($this->data['auto_timestamp']) && $this->data['auto_timestamp']) {
            $autoTimestamp = '// 开启自动写入时间戳字段' . "\n"
                . tab(1) . 'protected $autoWriteTimestamp = true;';
        }

        return file_put_contents($file, str_replace(
                ["[FLEX]", "[MODULE]", "[CONTROLLER]", "[TABLE]", "[UTABLE]", "[AUTO_TIMESTAMP]"],
                [$flex, $module, $controller, $table, parseName($data['controller']), $autoTimestamp],
                $template
            )
        );
    }


    /**
     * 创建数据表
     */
    private function buildTable($path, $pathTemplate, $fileName, $tableName, $code, $data)
    {
        if (app()->env->get(SYSTEM . '.db_host') != '127.0.0.1' || SYSTEM == 'product') {
            json_response(0, '禁止操作线上数据库！');
        }
        if(isset($data['table']) && $data['table'] !=''){
            //从数据库生成直接返回
            return true;
        }
 
        // 一定别忘记表名前缀
        $tableName = isset($data['table_name']) && $data['table_name'] ?
            $data['table_name'] : app()->env->get(SYSTEM . '.db_pre') . parseName($data['controller']);

        // 在 MySQL 中，DROP TABLE 语句自动提交事务，因此在此事务内的任何更改都不会被回滚，不能使用事务
        // http://php.net/manual/zh/pdo.rollback.php
        $tableExist = false;
        // 判断表是否存在

        $ret = Db::query("SHOW TABLES LIKE '{$tableName}'");
       
        // 表存在
        if ($ret && isset($ret[0])) {
            //不是强制建表但表存在时直接return
            if (!isset($data['create_table_force']) || !$data['create_table_force']) {
                return true;
            }
            Db::execute("RENAME TABLE {$tableName} to {$tableName}_build_bak");
            $tableExist = true;
        }
        $auto_create_field = ['id', 'create_time', 'update_time'];
        // 强制建表和不存在原表执行建表操作
        $fieldAttr     = [];
        $key           = [];
        $data['title'] = '';
        if (in_array('id', $auto_create_field)) {
            $fieldAttr[] = tab(1) . "`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '{$data['title']}主键'";
        }
        foreach ($this->data['field'] as $field) {
            if (!in_array($field['name'], $auto_create_field)) {
                // 字段属性
                $fieldAttr[] = tab(1) . "`{$field['name']}` {$field['type']}"
                    . ($field['extra'] ? ' ' . $field['extra'] : '')
                    . (isset($field['not_null']) && $field['not_null']===true ? ' NOT NULL' : '')
                    . (strtolower($field['default']) == 'null' ? '' : " DEFAULT '{$field['default']}'")
                    . ($field['comment'] === '' ? '' : " COMMENT '{$field['comment']}'");
            }
            // 索引
            if (isset($field['key']) && $field['key']=== true && $field['name'] != 'id') {
                $key[] = tab(1) . "KEY `{$field['name']}` (`{$field['name']}`)";
            }
        }


        // 如果创建模型则自动生成create_time，update_time字段
        if (isset($data['auto_timestamp']) && $data['auto_timestamp']) {
            // 自动生成 create_time 字段，相应自动生成的模型也开启自动写入create_time和update_time时间，并且将类型指定为int类型
            // 时间戳使用方法见：http://www.kancloud.cn/manual/thinkphp5/138668
            $fieldAttr[] = tab(1) . "`create_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间'";
            $fieldAttr[] = tab(1) . "`update_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间'";
        }
        // 自动生成 create_time 字段，相应自动生成的模型也开启自动写入create_time和update_time时间，并且将类型指定为int类型
        // 时间戳使用方法见：http://www.kancloud.cn/manual/thinkphp5/138668

        // 默认自动创建主键为id
        $fieldAttr[] = tab(1) . "PRIMARY KEY (`id`)";

        // 会删除之前的表，会清空数据，重新创建表，谨慎操作
        $sql_drop = "DROP TABLE IF EXISTS `{$tableName}`";
        // 默认字符编码为utf8，表引擎默认InnoDB，其他都是默认
        $sql_create = "CREATE TABLE `{$tableName}` (\n"
            . implode(",\n", array_merge($fieldAttr, $key))
            . "\n)ENGINE=" . (isset($this->data['table_engine']) ? $this->data['table_engine'] : 'InnoDB')
            . " DEFAULT CHARSET=utf8 COMMENT '{$data['title']}'";


        // 写入执行的SQL到日志中，如果不是想要的表结构，请到日志中搜索BUILD_SQL，找到执行的SQL到数据库GUI软件中修改执行，修改表结构
        Log::write("BUILD_SQL：\n{$sql_drop};\n{$sql_create};", 'sql');
        // execute和query方法都不支持传入分号 (;)，不支持一次执行多条 SQL
        try {
            Db::execute($sql_drop);
            Db::execute($sql_create);
            Db::execute("DROP TABLE IF EXISTS `{$tableName}_build_bak`");
        } catch (\Exception $e) {
            // 模拟事务操作，滚回原表
            if ($tableExist) {
                Db::execute("RENAME TABLE {$tableName}_build_bak to {$tableName}");
            }

            throw new Exception($e->getMessage().$e->getLine());
        }
    }

    private function buildValidator($pathView, $pathTemplate, $fileName, $tableName, $code, $data)
    {
        $app_path = dirname(dirname($_SERVER['SCRIPT_FILENAME']) . DS);
        // 直接生成空模板
        $template = file_get_contents($pathTemplate . "Validator.tpl");

        // 获取模型的路径，根据配置文件读取
        $module = $data['module'];
        $class  = parseName(str_replace(config('database.prefix'), '', $data['table']),1);
        $file   = $app_path . DS . 'app' . DS . $module . DS . "validate" . DS . $class . "Validate.php";
        $rule = "";
        $field = "";
        $scene = [];

        foreach ($data['form'] as $value){
            $rule .= "'{$value['field']}' => '".str_replace(',','|',$value['rule'])."|{$value['rule2']}',".PHP_EOL;
            $field .= "'{$value['field']}' => '{$value['comment']}',".PHP_EOL;
            $scene['edit'][] = "'{$value['field']}'";
            if($value['field'] != 'id') $scene['add'][] = "'{$value['field']}'";
            if($value['field'] == 'id') $scene['del'][] = "'{$value['field']}'";
        }

        $scene_edit = implode(",",$scene['edit']);
        $scene_add = implode(",",$scene['add']);
        $scene_del = implode(",",$scene['del']);

        return file_put_contents($file, str_replace(
                ["[MODULE]", "[CLASS]", "[RULE]", "[FIELD]", "[SCENE_ADD]","[SCENE_EDIT]","[SCENE_DEL]"],
                [$module, $class.'Validate', $rule,$field, $scene_add,$scene_edit,$scene_del],
                $template
            )
        );
    }


    /**
     * 创建文件的代码
     * @return array
     */
    private function parseCode()
    {


        $where_item = ''; //前端搜索条件
        $search     = ''; //接口搜索条件
        $form_item  = ''; //表单前端代码
        $validate_data   = '';  //表单验证数据
        $validate_msg  = '';//表单验证提示
        $validate     = ''; //前端验证
        $table_item = ''; //表格列表前端代码
        $import_item =''; //导入模板
        $components  = ''; //组件
        $create_methods    = ''; //创建方法   
        $edit_methods      = ''; //创建方法   
        $form_data    = ''; //vuedata数据
        $submit_data   = ''; //提交数据
        $detail_data   = ''; //详情数据 
        $edit_data     = ''; //编辑数据
        $create_button ='';
        $detail_button ='';
        $edit_button  ='';
        $delete_button= '';
        $batch_button= '';
        $export_button= '';
        $import_button= '';
        $detail_dialog = ''; //详情对话框
        $edit_dialog = ''; //编辑对话框
        $create_dialog = ''; //创建对话框
        $import  = ''; //前端引入
        $index_components = '';//首页引入组件
        $index_data    = '' ; //首页data
        $index_batch   = ''; //首页批量数据操作
        $index_method  = ''; //首页方法
        $batch_select = ''; //批量选择多选框
        $controller = strtolower($this->data['controller']);
        if(isset($this->data['create_button']) && $this->data['create_button']){
            //创建按钮
            $create_button = <<<EOF
            <el-button v-waves :disabled="!checkPermission(['$controller.create'])"  class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
                {{ "添加" }}
            </el-button>  
EOF;
            //创建对话框
            $create_dialog = <<<EOF
    <el-dialog :title="'添加'" :visible.sync="create.dialogVisible" @close="getList"  :close-on-click-modal=false>
                <create :item="create" />
            </el-dialog>
EOF;
//导入添加组件
$import  .= <<<EOF
    import Create from './components/create' // 添加组件  \r\n
EOF;
//引入添加组件
$index_components  .= <<<EOF
Create,
EOF;
//首页data
$index_data  .= <<<EOF
create: { // 新增
                 dialogVisible: false
                },  \r\n
EOF;
$index_method .= <<<EOF
        handleCreate() { // 新增对话框显示
            this.create.dialogVisible = true
        },  \r\n
EOF;

        }
        if(isset($this->data['detail_button']) && $this->data['detail_button']){
            //详情按钮
            $detail_button = <<<EOF
<el-button v-waves :disabled="!checkPermission(['$controller.detail'])" size='mini'  type="info" icon="el-icon-info" @click="handleDetail(scope.\$index, scope.row)">
                         {{ "详情" }}
                    </el-button>
EOF;
  //详情对话框
  $detail_dialog = <<<EOF
    <el-dialog :title="'详情'" :visible.sync="detail.dialogVisible" v-if="detail.dialogVisible">
                    <detail :data="detail.data" />
            </el-dialog>
EOF;
//引入详情组件
$import  .= <<<EOF
    import Detail from '@/components/Detail/detail' // 详情组件 \r\n
EOF;
//使用详情组件
$index_components  .= <<<EOF
Detail,
EOF;
//首页data
$index_data  .= <<<EOF
            detail: { // 详情
                   dialogVisible: false,
                   data: []
                },  \r\n
EOF;
$index_method .=<<<EOF
        handleDetail(index, row) { // 详情
            detail(row.id).then((res) => {
                    this.detail.dialogVisible = true
                    const data = res.data
                    this.detail.data = [
                    [DETAIL]
                    ]
                })
            },  \r\n
EOF;

        }
    if(isset($this->data['edit_button']) && $this->data['edit_button']){
            //编辑按钮
            $edit_button = <<<EOF
<el-button v-waves v-permission="['$controller.edit']"  type="primary"  size='mini' icon="el-icon-edit" @click="handleEdit(scope.\$index, scope.row)">
                         {{ "编辑" }}
                    </el-button>
EOF;
           //编辑对话框
           $edit_dialog = <<<EOF
    <el-dialog :title="'编辑'" :visible.sync="edit.dialogVisible" @close="getList" :close-on-click-modal=false>
              <edit :item="edit" />
          </el-dialog>
EOF;
$import  .= <<<EOF
    import Edit from './components/edit'  // 编辑组件  \r\n
EOF;
//使用编辑组件
$index_components  .= <<<EOF
Edit
EOF;
//首页data
$index_data  .= <<<EOF
            edit: { // 编辑
                 dialogVisible: false,
                 id: ''
            },  \r\n
EOF;
$index_method .=<<<EOF
        handleEdit(index, row) { // 编辑对话框显示
            this.edit.dialogVisible = true
            this.edit.id = row.id
        },  \r\n
EOF;

        }
        if($this->data['delete_button'] && $this->data['delete_button']){
            //删除按钮
            $delete_button = <<<EOF
<el-button v-waves v-permission="['$controller.delete']"  type="danger" :destroy-on-close="true" size='mini' icon="el-icon-delete" @click="handleDelete(scope.\$index, scope.row)">
                         {{ "删除" }}
                    </el-button>
EOF;
$index_method .= <<<EOF
        handleDelete(index, row) { // 删除
            const thiz = this
            this.\$confirm('确认要删除吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                del(row.id).then(() => {
                this.\$message({
                    message: '删除成功',
                    type: 'success',
                    duration: 1500,
                    onClose() {
                        thiz.list.splice(index, 1)
                    }
                })
                })
            }).catch(() => {

            })
        },   \r\n
EOF;
        }
        if($this->data['batch_button'] && $this->data['batch_button']){
            //批量操作按钮
            $batch_button = <<<EOF
    <el-button v-waves :disabled="!checkPermission(['$controller.delete'])" class="filter-item" type="danger" icon="el-icon-delete" @click="handleBatch">
                {{ '批量删除' }}
            </el-button>
EOF;
$index_data .= <<<EOF
            select_ids : [], // 选中的id集合  \r\n
EOF;
$index_batch .= <<<EOF
@select="handleSelect"
                @select-all ="selectAll"
EOF;
$batch_select = <<<EOF
    <el-table-column align="center" type="selection" width="55"></el-table-column>  \r\n
EOF;
$index_method .= <<<EOF
            handleSelect(selection, row) { // 选中
                this.select_ids = [];
            selection.map(item => {
                    this.select_ids.push(item.id);
            })
            },
            selectAll(selection) { // 全选
                this.select_ids = [];
                selection.map(item => {
                    this.select_ids.push(item.id);
                })
            },
            handleBatch() {  // 批量删除
                var that = this;
                if(this.select_ids.length == 0){
                    this.\$message({
                        message: '请选择要删除的数据',
                        type: 'warning'
                    });
                    return false;
                }
                this.\$confirm('确认删除选中的数据?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    del(this.select_ids.join(',')).then(res => {
                        this.\$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getList();
                    }).catch(err => {
                        this.\$message({
                            message: err.msg,
                            type: 'error'
                        });
                    })
                }).catch(() => {
                    this.\$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },   \r\n
EOF;

        }
if($this->data['export_button'] && $this->data['export_button']){
            //导出按钮
            $export_button = <<<EOF
            <el-button v-waves :disabled="!checkPermission(['$controller.export'])"  type="success" icon="el-icon-upload2" @click="handleExport">
                {{ '导出' }}
            </el-button>
EOF;
$export = '_export';
$index_method .= <<<EOF
    handleExport(){
            let query="";
            for ( let key in this.listQuery) {
                query+= `\${key}=\${this.listQuery[key]}&`
            }
            window.location.href = process.env.VUE_APP_BASE_API + `admin/$controller$export?\${query}`;
        },  \r\n
EOF;
    //   $methods .= tab(4)."handleExport(){
    //     export_excell(process.env.VUE_APP_BASE_API+'/admin/".$controller."_exports',this.listQuery);
    // },";
    }
if($this->data['import_button'] && $this->data['import_button']){
    //导入作按钮
    $import_text = '_import';
    $import_button .= tab(4) . '<el-upload
                     class="import"
                     :action="import_url"
                     v-loading="import_loading"
                     accept=".csv"
                     :headers ="headerObj"
                     :before-upload="beforeImport"
                     :on-success="handleImport"
                     :show-file-list="false"
                    >
                     <el-button icon="el-icon-download" type="primary">导入</el-button>
                </el-upload>';
    $index_data .= <<<EOF
            import_url: process.env.VUE_APP_BASE_API+'/admin/$controller$import_text',
            import_loading : false
EOF;
$index_method .= <<<EOF
    beforeImport() { //导入前回调
        this.import_loading = true
      },  \r\n
      
    handleImport(res) { // 导入
        if (!res.code) {
          this.\$message.error(res.msg)
        } else {
          this.\$message.success(res.msg);
          this.getList()
        }
        this.import_loading = false;
      },
EOF;
}
        
        foreach($this->data['form'] as $form){
            if($form['type'] == 'images'){
                $form_data .=tab(3)."{$form['name']}:[],"."\n";
                $form_data .=tab(3)."{$form['name']}previewurl:'',"."\n";
                $form_data .=tab(3)."{$form['name']}fileList:[],"."\n";
            }elseif($form['type'] == 'imageone'){
                $form_data .=tab(3)."{$form['name']}:'',"."\n";
                $form_data .=tab(3)."{$form['name']}_loading:false,"."\n";
            }elseif($form['type'] == 'checkbox'){
                $form_data .=tab(3)."{$form['name']}:['1'],"."\n";
            }elseif($form['type'] == 'radio'){
                $form_data .=tab(3)."{$form['name']}:'1',"."\n";
            }elseif($form['type'] == 'date'){
                $form_data .=tab(3)."{$form['name']}:'".date('Y-m-d')."',"."\n";
            }elseif($form['type'] == 'datetime'){
                $form_data .=tab(3)."{$form['name']}:[],"."\n";
            }elseif($form['type'] == 'time'){
                $form_data .=tab(3)."{$form['name']}:'".date('H-i')."',"."\n";
            }elseif($form['type'] == 'video'){
                $form_data .=tab(3)."{$form['name']}:'',"."\n";
                $form_data .=tab(3)."{$form['name']}fileList:[],"."\n";
                $form_data .=tab(3)."{$form['name']}percentage:0,"."\n";
            }else{
                $form_data .=tab(3)."{$form['name']}:'',"."\n";
            }
            if($form['type'] == 'images'){
                $submit_data .=tab(3)."{$form['name']}:this.data.".$form['name'].".join(','),"."\n";
                $edit_data .= tab(3)."this.data.".$form['name']."=response.data.".$form['name']." ? response.data.".$form['name'].".split(',') : [];"."\n";
                $edit_data .= tab(3)."this.data.".$form['name']."fileList=response.data.".$form['name']." ? response.data.".$form['name'].".map(item=>{return{name:item,url:item}}):[];"."\n";
            }elseif($form['type'] == 'imageone'){
                $submit_data .=tab(3)."{$form['name']}:this.data.".$form['name'].","."\n";
            }elseif($form['type'] == 'checkbox' || $form['type'] == 'selects'){
                $submit_data .=tab(3)."{$form['name']}:this.data.".$form['name'].".join(','),"."\n";
                $edit_data .= tab(3)."this.data.".$form['name']."=response.data.".$form['name']." ? response.data.".$form['name'].".split(','):[];"."\n";
            }elseif($form['type'] == 'datetime'){
                $submit_data .=tab(3)."{$form['name']}:this.data.".$form['name'].".join('/'),"."\n";
                $edit_data .=tab(3)."this.data.".$form['name']."=response.data.".$form['name'].".split('/');"."\n";
            }elseif($form['type'] == 'video'){
                $edit_data .=tab(3)."this.data.".$form['name']."fileList=response.data.".$form['name']." ? [{name:response.data.".$form['name'].",url:response.data.".$form['name']."}] : [];"."\n";
                $submit_data .=tab(3)."{$form['name']}:this.data.".$form['name'].","  ."\n";
            }else{
                $submit_data .=tab(3)."{$form['name']}:this.data.".$form['name'].","  ."\n";
            }
            
            if($form['validate']){
                #验证规则
                $validate .= tab(3).''.$form['name'].': [ '."\n";
                $validate .=  tab(4). '{ required: true, message: "请输入'.$form['title'].'", trigger: "blur" }'."\n";
                $validate .=  tab(3).'], '."\n";
                $validate_data  .= tab(4)."'{$form['name']}'" . '=>' . "'require'".','."\n";
                $validate_msg   .= tab(4)."'{$form['name']}.require'". '=>'."'{$form['title']}不得为空'".',' ."\n";
            }
            if(isset($form['search']) && $form['search']){
                $search .= tab(3) . 'if(isset($search["' . $form["name"] . '"]) && $search["' . $form["name"] . '"]!="") $where[] = ["' . $form["name"] . '","=",$search["' . $form["name"] . '"]];' . "\n"; //后端搜索条件
            }
    
            if(isset($form['show']) && $form['show'] ==1){
                $table_item .=      tab(3) .'<el-table-column  align="center" label="'.$form['title'].'">' ."\n";
                $table_item .=      tab(4). '<template slot-scope="scope">' ."\n";
                                    if(trim($form['type']) == 'imageone'){
                                        $table_item .=   tab(5).  '<el-image   :preview-src-list="scope.row.'.$form['name'].' ? scope.row.'.$form['name'].'.split(\',\') : []" style="width: 50px; height: 50px" :src="scope.row.'.$form['name'].'" fit="cover"></el-image>' ."\n";
                                    }elseif(trim($form['type']) == 'images'){
                                        $table_item .= tab(5). '<el-image style="width: 50px; height: 50px;margin-right:5px"  v-for="(item,ids) in scope.row.'.$form['name'].'.split(\',\')" :key="ids" :preview-src-list="scope.row.'.$form['name'].' ? scope.row.'.$form['name'].'.split(\',\'):[]" :src="item" fit="cover"></el-image>' ."\n";
                                    }elseif($form['type'] == 'switch'){
                                        $table_item .= tab(5).'  <el-tag   v-if="scope.row.'.$form['name'].' == \'1\'" type="success" size="mini">'."\n";
                                        $table_item .= tab(5).      '开 '."\n";
                                        $table_item .= tab(5).   '</el-tag>'."\n";
                                        $table_item .= tab(5).  '<el-tag   v-else type="danger" size="mini">'."\n";
                                        $table_item .= tab(5).    ' 关 '."\n";
                                           $table_item .= tab(5). '</el-tag>'."\n";
                                    }else{
                                        $table_item .=     tab(5). '<span>{{ scope.row.'.$form['name'].' }}</span>' ."\n";
                                    }
                $table_item  .=           tab(4) .'</template>'."\n";
                $table_item .=       tab(3) .'</el-table-column>' ."\n";
            }
            
          if (isset($form['search']) && $form['search']) {
                switch ($form['search_type']) {
                    case 'text':
                        $where_item .= tab(5) . '<el-input v-model="listQuery.'.$form['name'].'" placeholder="请输入'.$form['title'].'" clearable style="width: 200px;margin-right: 10px;margin-bottom:10px" class="filter-item" @keyup.enter.native="handleFilter" />' . "\n";
                        break;
                    case 'select':
                        $where_item .= tab(5).'<el-select v-model="listQuery.'.$form['name'].'" placeholder="请选择'.$form['title'].'" clearable style="width: 200px;margin-right: 10px;" class="filter-item" @keyup.enter.native="handleFilter" >' . "\n";
                        $where_item .= tab(6).'<el-option  label="选项1" value="选项1"></el-option>' . "\n";
                        $where_item .= tab(5).'</el-select>' . "\n";
                        break;
                    case 'date':
                        $where_item .= tab(5) . '<el-date-picker v-model="listQuery.' . $form["name"] . '" type="daterange"  style="width: 200px;margin-right: 10px;margin-bottom:10px" start-placeholder="开始日期"
                        end-placeholder="结束日期"  range-separator="-" placeholder="请选择' . $form['title'] . '"     @keyup.enter.native="handleFilter" />' . "\n";
                        break;
                    case 'time':
                        $where_item .= tab(5) . '<el-time-picker v-model="listQuery.' . $form["name"] . '" is-range  start-placeholder="开始时间"
                        end-placeholder="结束时间"  range-separator="-" placeholder="请选择' . $form['title'] . '"     @keyup.enter.native="handleFilter" />' . "\n";
                        $where_item .= tab(5) .' </el-time-picker>' . "\n";
                        break;
                    default:
                        # code...
                        break;
                }
            }
            switch (trim($form['type'])) {
                case 'text':
                    $form_item .= tab(5) . '<el-form-item label="'.$form['title'].'" prop="'.$form['name'].'">' ."\n";
                    $form_item .= tab(6) . '<el-input v-model.trim="data.'.$form['name'].'" placeholder="请填写'.$form['title'].'" />' ."\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].','."\n";
                    $detail_data .= tab(5).'type: "text"'."\n";
                    $detail_data .= tab(4).'},'."\n";
                    break;
                case 'select':
                    $form_item .= tab(5) . '<el-form-item label="'.$form['title'].'" prop="'.$form['name'].'">' ."\n";
                    $form_item .= tab(5).'<el-select v-model.trim="data.'.$form['name'].'" placeholder="请选择'.$form['title'].'" clearable  class="filter-item" >' . "\n";
                    $form_item .= tab(6).'<el-option  label="选项1" value="1"></el-option>' . "\n";
                    $form_item .= tab(5).'</el-select>' . "\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].','."\n";
                    $detail_data .= tab(5).'type: "text"'."\n";
                    $detail_data .= tab(4).'},'."\n";
                    break;
                case 'selects':
                    $form_item .= tab(5) . '<el-form-item label="'.$form['title'].'" prop="'.$form['name'].'">' ."\n";
                    $form_item .= tab(5).'<el-select v-model.trim="data.'.$form['name'].'" multiple  placeholder="请选择'.$form['title'].'" clearable  class="filter-item" >' . "\n";
                    $form_item .= tab(6).'<el-option  label="选项1" value="1"></el-option>' . "\n";
                    $form_item .= tab(6).'<el-option  label="选项2" value="2"></el-option>' . "\n";
                    $form_item .= tab(5).'</el-select>' . "\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].','."\n";
                    $detail_data .= tab(5).'type: "text"'."\n";
                    $detail_data .= tab(4).'},'."\n";
                    break;
                case 'imageone':
                    $form_item .= tab(5) . '<el-form-item label="'.$form['title'].'" prop="'.$form['name'].'" >' ."\n";
                    $form_item .= tab(6) .'<el-upload
                    class="avatar-uploader"
                    v-loading="data.'.$form['name'].'_loading"
                    element-loading-text="图片上传中"
                    :action="$store.state.settings.file_upload_url"
                    :headers ="headerObj"
                    :show-file-list="false"
                    accept="image/png, image/jpeg, image/gif, image/jpg"
                    :on-success="handle'.$form['name'].'Success"
                    :before-upload="before'.$form['name'].'Upload">
                        <img v-if="data.'.$form['name'].'" :src="data.'.$form['name'].'" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>'."\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    $create_methods = $edit_methods .=  tab(2). ' handle'.$form['name'].'Success(response, file, fileList) {' . "\n";
                    $create_methods = $edit_methods .= tab(4).  'this.$store.commit(\'settings/SET_AJAX_BUTTON\', false);' . "\n";
                    $create_methods = $edit_methods .= tab(4).  'this.data.'.$form['name'].'_loading = false '. "\n";
                    $create_methods = $edit_methods .= tab(5).  ' if(response.data.code == 0){' . "\n";
                    $create_methods = $edit_methods .= tab(6).  ' this.data.'.$form['name'].'fileList = []' . "\n";
                    $create_methods = $edit_methods .= tab(5).  ' return this.$message.error(response.msg);' . "\n";
                    $create_methods = $edit_methods .=  tab(3). '}' . "\n";
                    $create_methods = $edit_methods .=  tab(4). 'this.data.'.$form['name'].'= response.data.src;' . "\n";
                    $create_methods = $edit_methods .=  tab(3). '},' . "\n";
                    $create_methods = $edit_methods .=  tab(3). ' before'.$form['name'].'Upload(file) {' . "\n";
                    $create_methods = $edit_methods .= tab(4).  'this.data.'.$form['name'].'_loading = true '. "\n";
                    $create_methods = $edit_methods .= tab(4).  'this.$store.commit(\'settings/SET_AJAX_BUTTON\', true);' . "\n";
                    $create_methods = $edit_methods .=  tab(4). 'const isJPG = file.type === "image/jpeg";' . "\n";
                    $create_methods = $edit_methods .=  tab(4). 'const isPNG = file.type === "image/png";' . "\n";
                    $create_methods = $edit_methods .=  tab(4). 'if (!isJPG && !isPNG) {' . "\n";
                    $create_methods = $edit_methods .=  tab(4). ' return this.$message.error("上传头像图片只能是 JPG 、PNG格式!");' . "\n";
                    $create_methods = $edit_methods .=  tab(4). '}' . "\n";
                    $create_methods = $edit_methods .=  tab(3). '},' . "\n";
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].','."\n";
                    $detail_data .= tab(5).'type: "image"'."\n";
                    $detail_data .= tab(4).'},'."\n";
                    break;
                case 'images':
                    $form_item .= tab(5) . '<el-form-item label="'.$form['title'].'" prop="'.$form['name'].'">' ."\n";
                    $form_item .= tab(6) .'<el-upload
                    :action="$store.state.settings.file_upload_url"
                    :headers ="headerObj"
                    multiple
                    list-type="picture-card"
                    :on-preview="handle'.$form['name'].'Preview"
                    :file-list="data.'.$form['name'].'fileList"
                    accept="image/png, image/jpeg, image/gif, image/jpg"
                    :on-success="handle'.$form['name'].'Success"
                    :on-remove="handle'.$form['name'].'Remove"
                    >
                     <i class="el-icon-plus"></i>
                    </el-upload>'."\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    $create_methods = $edit_methods .= tab(3) . ' handle'.$form['name'].'Preview(file) {' . "\n";
                    $create_methods = $edit_methods .=  tab(4). 'this.dialogVisible = true;' . "\n";
                    $create_methods = $edit_methods .=  tab(4). 'this.previewUrl = file.url;' . "\n";
                    $create_methods = $edit_methods .= tab(3) .'},'. "\n";
                    $create_methods = $edit_methods .=  tab(3).' handle'.$form['name'].'Success(response, file, fileList) {' . "\n";
                    $create_methods = $edit_methods .= tab(4). 'this.$store.commit(\'settings/SET_AJAX_BUTTON\', false);' . "\n";
                    $create_methods = $edit_methods .= tab(3).  ' if(!response.data.src){' . "\n";
                    $create_methods = $edit_methods .= tab(4).  ' this.data.'.$form['name'].'fileList = []' . "\n";
                    $create_methods = $edit_methods .= tab(4).  ' return this.$message.error(response.msg);' . "\n";
                    $create_methods = $edit_methods .=  tab(3). '}' . "\n";
                    $create_methods = $edit_methods .= tab(4). ' this.data.'.$form['name'].'.push(response.data.src);' . "\n";
                    $create_methods = $edit_methods .=  tab(3). '},' . "\n";
                    $create_methods = $edit_methods .=  tab(3).' before'.$form['name'].'Upload(file) {' . "\n";
                    $create_methods = $edit_methods .= tab(4). 'this.$store.commit(\'settings/SET_AJAX_BUTTON\', true);' . "\n";
                    $create_methods = $edit_methods .=  tab(4). 'const isJPG = file.type === "image/jpeg";' . "\n";
                    $create_methods = $edit_methods .=  tab(4). 'const isPNG = file.type === "image/png";' . "\n";
                    $create_methods = $edit_methods .=  tab(4). 'const isLt2M = file.size / 1024 / 1024 < 2;' . "\n";
                    $create_methods = $edit_methods .=  tab(4). 'if (!isJPG && !isPNG) {' . "\n";
                    $create_methods = $edit_methods .=  tab(4). ' return this.$message.error("上传头像图片只能是 JPG 、PNG格式!");' . "\n";
                    $create_methods = $edit_methods .=  tab(4). '}' . "\n";
                    $create_methods = $edit_methods .=  tab(3). '},' . "\n";
                    $edit_methods .=  tab(3).' handle'.$form['name'].'Remove(file,fileList) {' . "\n";
                    $edit_methods .=  tab(4). 'const that = this;' . "\n";
                    $edit_methods .=  tab(4). 'let index = this.data.'.$form['name'].'fileList.findIndex(item=>item.url==file.url);' . "\n";
                    $edit_methods .=  tab(4). ' if(index!=-1) {' . "\n";
                    $edit_methods .=  tab(5). ' this.data.'.$form['name'].'fileList.splice(index, 1);' . "\n";
                    $edit_methods .=  tab(5). ' this.data.'.$form['name'].'.splice(index, 1);' . "\n";
                    $edit_methods .=  tab(4). '}' . "\n";
                    $edit_methods .=  tab(3). '},' . "\n";
                    $create_methods .=  tab(3).' handle'.$form['name'].'Remove(file,fileList) {' . "\n";
                    $create_methods .=  tab(4). 'const that = this;' . "\n";
                    $create_methods .=  tab(4). 'let index = this.data.'.$form['name'].'fileList.findIndex(item=>item.url==file.url);' . "\n";
                    $create_methods .=  tab(4). ' if(index!=-1) {' . "\n";
                    $create_methods .=  tab(5). ' this.data.'.$form['name'].'fileList.splice(index, 1);' . "\n";
                    $create_methods .=  tab(5). ' this.data.'.$form['name'].'.splice(index, 1);' . "\n";
                    $create_methods .=  tab(4). '}' . "\n";
                    $create_methods .=  tab(3). '},' . "\n";
                    
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].'.split(","),'."\n";
                    $detail_data .= tab(5).'type: "images"'."\n";
                    $detail_data .= tab(4).'},'."\n";
                    break;
                case 'video':
                    $form_item .= tab(5).'<el-form-item label="'.$form['title'].'" prop="'.$form['name'].'">' ."\n";
                    $form_item .=   tab(6). '<el-upload' . "\n";    
                    $form_item .=  tab(5) .'action="#"'. "\n";
                    $form_item .= tab(5) .'ref="'.$form['name'].'" :auto-upload="false" :file-list = "data.'.$form['name'].'fileList" :on-change="videoChange'.$form['name'].'" class="avatar-uploader"  accept=".mp4" :on-remove="handleRemove'.$form['name'].'">'."\n";
                    $form_item .= tab(5) .'<video ref="'.$form['name'].'"  v-if="data.'.$form['name'].'"  controls style="width: 320px;height: 180px;" :src="data.'.$form['name'].'"></video>'."\n";
                    $form_item .=  tab(5) .'<i v-else class="el-icon-plus avatar-uploader-icon"></i>'."\n";
                    $form_item .=  tab(6) .'</el-upload>'."\n";
                    $form_item .= tab(5) .'<el-progress  v-show="data.'.$form['name'].'percentage>0 && data.'.$form['name'].'percentage<100" :percentage="data.'.$form['name'].'percentage" :text-inside="true" :stroke-width="18"></el-progress>'."\n";
                    $form_item .=  tab(5) . '</el-form-item>'."\n";
                    $import_item .= "import videoUpload from '@/utils/videoUpload'" . "\n";
                    $create_methods = $edit_methods .=   tab(5) . ' handleRemove'.$form['name'].'() {' . "\n";
                    $create_methods = $edit_methods .= tab(6) . 'this.data.'.$form['name'].' = "";' . "\n";
                    $create_methods = $edit_methods .= tab(6) . 'this.data.'.$form['name'].'fileList = [];' . "\n";
                    $create_methods = $edit_methods .= tab(5) . '},' . "\n";
                    $create_methods = $edit_methods .= tab(2) . 'videoChange'.$form['name'].'(file, fileList) {' . "\n";
                    $create_methods = $edit_methods .= tab(3) . '  var that = this;' . "\n";
                    $create_methods = $edit_methods .= tab(3) . 'get_video_config().then(res=>{' . "\n";
                    $create_methods = $edit_methods .= tab(4) . '   if(res.code && res.code==1 && res.data.uploadType !=\'local\'){ ' . "\n";
                    $create_methods = $edit_methods .= tab(5) . '   videoUpload.upload(res.data.uploadType,{' . "\n";
                    $create_methods = $edit_methods .= tab(6) . '   token: "",' . "\n";
                    $create_methods = $edit_methods .= tab(6) . '   file: file,' . "\n";
                    $create_methods = $edit_methods .= tab(6) . '   accessKeyId: res.data.accessKey,' . "\n";
                    $create_methods = $edit_methods .= tab(6) . '   accessKeySecret: res.data.secretKey,' . "\n";
                    $create_methods = $edit_methods .= tab(6) . '   bucketName:res.data.storageName,' . "\n";
                    $create_methods = $edit_methods .= tab(6) . '   region: res.data.storageRegion,' . "\n";
                    $create_methods = $edit_methods .= tab(6) . '   domain: res.data.uploadUrl,' . "\n";
                    $create_methods = $edit_methods .= tab(6) . '   static_path: res.data.static_path,' . "\n";
                    $create_methods = $edit_methods .= tab(6) . '   static_url :res.data.static_url,' . "\n";
                    $create_methods = $edit_methods .= tab(6) . '   uploadIng:function (progress) {' . "\n";
                    $create_methods = $edit_methods .= tab(7) . '    that.$set(that.data,"'.$form['name'].'percentage",progress);' . "\n";
                    $create_methods = $edit_methods .= tab(6) . '  }' . "\n";
                    $create_methods = $edit_methods .= tab(5) . ' }).then(function (res) {' . "\n";
                    $create_methods = $edit_methods .=  tab(7) . ' that.data.'.$form['name'].' = res.url;' . "\n";
                    $create_methods = $edit_methods .= tab(7) . '  that.$message.success("上传成功");' . "\n";
                    $create_methods = $edit_methods .=  tab(6) . '      }).catch(function (err) {' . "\n";
                    $create_methods = $edit_methods .= tab(6) . '   return  that.$message.error(err);' . "\n";
                    $create_methods = $edit_methods .= tab(6) . '    });' . "\n";
                    $create_methods = $edit_methods .= tab(4) . '      }else if(res.data.uploadType ==\'local\'){' . "\n";
                    $create_methods = $edit_methods .= tab(5) . '      const fd = new FormData()' . "\n";   
                    $create_methods = $edit_methods .= tab(5) . '      fd.append(\'file\', file.raw)' . "\n";   
                    $create_methods = $edit_methods .= tab(5) . '      upload_file(fd,function(progress){' . "\n";   
                    $create_methods = $edit_methods .= tab(5) . '      if(progress.lengthComputable){' . "\n";
                    $create_methods = $edit_methods .= tab(5) . '      var percentCompleted = Math.round( (progress.loaded * 100) / progress.total );' . "\n";
                    $create_methods = $edit_methods .= tab(5) . '      that.$set(that.data,"demo_videopercentage",percentCompleted);' . "\n";
                    $create_methods = $edit_methods .= tab(5) . '       }' . "\n";
                    $create_methods = $edit_methods .= tab(5) . '     }).then((res) => {' . "\n";       
                    $create_methods = $edit_methods .= tab(5) . '       if(res.code ==1){' . "\n";  
                    $create_methods = $edit_methods .= tab(5) . '       that.data.demo_video = res.data.src;' . "\n";  
                    $create_methods = $edit_methods .= tab(5) . '          }else{' . "\n"; 
                    $create_methods = $edit_methods .= tab(5) . '       return  that.$message.error(res.msg);' . "\n";   
                    $create_methods = $edit_methods .= tab(5) . '       }' . "\n";  
                    $create_methods = $edit_methods .= tab(5) . '        })' . "\n";  
                    $create_methods = $edit_methods .= tab(5) . '        }else{' . "\n";  
                    $create_methods = $edit_methods .= tab(5) . '     return this.$message.error("获取上传配置失败，请检查");' . "\n";
                    $create_methods = $edit_methods .=tab(4) . '}' . "\n";
                    $create_methods = $edit_methods .=tab(3) . ' });' . "\n";
                    $create_methods = $edit_methods .=tab(2) . '},' . "\n";
                    $import_item .= "import {get_video_config,upload_file} from '@/api/common'" . "\n";
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].','."\n";
                    $detail_data .= tab(5).'type: "video"'."\n";
                    $detail_data .= tab(4).'},'."\n";
                    break;
                case 'textarea':
                    $form_item .= tab(5) . ' <el-form-item label="'.$form['title'].'" prop="'.$form['name'].'">'."\n";
                    $form_item .= tab(6) . '<el-input type="textarea" v-model.trim="data.'.$form['name'].'" placeholder="请填写'.$form['title'].'"  rows="6" />' ."\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].','."\n";
                    $detail_data .= tab(5).'type: "text"'."\n";
                    $detail_data .= tab(4).'},'."\n";
                    break;
                case 'editor':
                    $form_item .= tab(5) . '<el-form-item label="'.$form['title'].'" prop="'.$form['name'].'">'."\n";
                    $form_item .= tab(6) . ' <editor
                  v-model="data.'.$form['name'].'"
                   v-if="this.item.dialogVisible"
                  />' ."\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    $import_item .= "import editor from '@/components/Editor'" . "\n";
                    $components = "editor";
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].','."\n";
                    $detail_data .= tab(5).'type: "html"'."\n";
                    $detail_data .= tab(4).'},'."\n";
                    break;
                case 'number':
                    $form_item .= tab(5) . '<el-form-item label="'.$form['title'].'" prop="'.$form['name'].'">' ."\n";
                    $form_item .= tab(6) . '<el-input-number v-model="data.'.$form['name'].'" :min="1" :max="10" label="'.$form['title'].'"></el-input-number>' ."\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].','."\n";
                    $detail_data .= tab(5).'type: "text"'."\n";
                    $detail_data .= tab(4).'},'."\n";
                    break;
                case 'password':
                    $form_item .= tab(5) . '<el-form-item label="'.$form['title'].'" prop="'.$form['name'].'">' ."\n";
                    $form_item .= tab(6) . '<el-input v-model.trim="data.'.$form['name'].'" show-password placeholder="请填写'.$form['title'].'" />' ."\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    break;
                case 'checkbox':
                    $form_item .= tab(5) . '<el-form-item label="'.$form['title'].'">' ."\n";
                    $form_item .= tab(6) .' <el-checkbox-group v-model="data.'.$form['name'].'">' ."\n";
                    $form_item .= tab(7) .' <el-checkbox label="1">选项1</el-checkbox>' ."\n";
                    $form_item .= tab(7) .' <el-checkbox label="2">选项2</el-checkbox>' ."\n";
                    $form_item .= tab(6) .' </el-checkbox-group>' ."\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].','."\n";
                    $detail_data .= tab(5).'type: "text"'."\n";
                    $detail_data .= tab(4).'},'."\n";
                    break;
                case 'switch':
                    $form_item .= tab(5) . '<el-form-item label="'.$form['title'].'">' ."\n";
                    $form_item .= tab(7) .' <el-switch :active-value="1" :inactive-value="0" v-model="data.'.$form['name'].'"></el-switch>' ."\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].','."\n";
                    $detail_data .= tab(5).'type: "switch"'."\n";
                    
                    $detail_data .= tab(4).'},'."\n";
                    break;
                case 'radio':
                    $form_item .= tab(5) . '<el-form-item label="'.$form['title'].'">' ."\n";
                    $form_item .= tab(6) .' <el-radio-group v-model="data.'.$form['name'].'">' ."\n";
                    $form_item .= tab(7) .' <el-radio label="1">选项1</el-radio>' ."\n";
                    $form_item .= tab(7) .' <el-radio label="2">选项2</el-radio>' ."\n";
                    $form_item .= tab(6) .' </el-radio-group>' ."\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].','."\n";
                    $detail_data .= tab(5).'type: "text"'."\n";
                    $detail_data .= tab(4).'},'."\n";
                    break;
                case 'date':
                    $form_item .= tab(5) . '<el-form-item label="'.$form['title'].'">' ."\n";
                    $form_item .= tab(6) .' <el-date-picker type="date" key="'.$form['name'].'" value-format="yyyy-MM-dd" placeholder="请选择日期" v-model="data.'.$form['name'].'"></el-date-picker>' ."\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].','."\n";
                    $detail_data .= tab(5).'type: "text"'."\n";
                    $detail_data .= tab(4).'},'."\n";
                    break;
                case 'time':
                    $form_item .= tab(5) . '<el-form-item label="'.$form['title'].'">' ."\n";
                    $form_item .= tab(6) .' <el-time-select  placeholder="请选择时间" v-model="data.'.$form['name'].'"></el-time-select>' ."\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].','."\n";
                    $detail_data .= tab(5).'type: "text"'."\n";
                    $detail_data .= tab(4).'},'."\n";
                    break;
                case 'datetime':
                    $form_item .= tab(5) . '<el-form-item label="'.$form['title'].'">' ."\n";
                    $form_item .= tab(6) .' <el-date-picker type="daterange" value-format="yyyy-MM-dd" placeholder="请选择日期" start-placeholder="开始日期" end-placeholder="结束日期" range-separator="/" v-model="data.'.$form['name'].'"></el-date-picker>' ."\n";
                    $form_item .= tab(5) . '</el-form-item>' ."\n";
                    $detail_data .= tab(4).'{'."\n";
                    $detail_data .= tab(5).'name:"'.$form['title'].'",'."\n";
                    $detail_data .= tab(5).'content:data.'.$form['name'].','."\n";
                    $detail_data .= tab(5).'type: "text"'."\n";
                    $detail_data .= tab(4).'},'."\n";
                    break;
                default:
                    
                    break;
            }
            
        }
 
        return [
            'table_item' => $table_item,
            'form_item' => $form_item,
            'import_item' => $import_item,
            'components' => $components,
            'validate_data' => $validate_data,
            'validate'   => $validate,
            'validate_msg' => $validate_msg,
            'where_item' => $where_item,
            'search' => $search,
            'form_data' => $form_data,
            'submit_data' => $submit_data,
            'create_methods' => $create_methods,
            'edit_methods' => $edit_methods,
            'edit_data' => $edit_data,
            'detail_data' => $detail_data,
            'create_button' => $create_button,
            'edit_button' => $edit_button,
            'detail_button' => $detail_button,
            'delete_button' => $delete_button,
            'batch_button' => $batch_button,
            'export_button' => $export_button,
            'import_button' => $import_button,
            'create_dialog'  => $create_dialog,
            'edit_dialog'   => $edit_dialog,
            'detail_dialog' => $detail_dialog,
            'import'        => $import,
            'index_components' => $index_components,
            'index_data'    => $index_data,
            'index_batch'   => $index_batch,
            'index_method' => $index_method,
            'batch_select'  => $batch_select
        ];
    }


}
